package com.shr.xsunmvc.db;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.sql.DataSource;

import org.sql2o.Connection;
import org.sql2o.Query;
import org.sql2o.Sql2o;

import com.shr.xsunmvc.db.mapper.TableMapper;
import com.shr.xsunmvc.db.sqlutil.GenerateSql;

public final class XsunDb {
	private static Sql2o sql2o = null;
	
	/**
	 * sql语句产生方式
	 */
	private static GenerateSql genrateSql ;
	
	private static List<Table> tableList = new ArrayList<>() ;
	
	
	private XsunDb() {
	}
	
	/**
	 * 初始化数据库配置
	 * @param url
	 * @param user
	 * @param pass
	 */
	public static void init(String url, String user, String pass, Type sqlType){
		sql2o = new Sql2o(url, user, pass);
		genrateSql = TypeFactory.getType(sqlType);
		setTableMapper();
	}
	
	/**
	 * 初始化数据库配置
	 * @param dataSource
	 */
	public static void init(DataSource dataSource, Type sqlType){
		sql2o = new Sql2o(dataSource);
		genrateSql = TypeFactory.getType(sqlType);
		setTableMapper();
	}
	

	private static void setTableMapper() {
		for(Table table : tableList){
			TableMapper.me().putTable(table);
		}
	}
	
	/**
	 * 返回产生sql语句的工具类对象
	 * @return
	 */
	public static GenerateSql getGenerateSql(){
		return genrateSql ;
	}

	
	/**
	 * 为数据库和Model设置映射关系
	 * @param tableName
	 * @param primaryKey
	 * @param clazz
	 */
	public static void setMapping(String tableName, String primaryKey, Class<? extends Model> clazz){
		tableList.add(new Table(tableName, primaryKey, clazz)) ;
	}
	
	/**
	 * 执行保存操作
	 * @param sql
	 * @param attributes
	 */
	public static int save(StringBuilder sql, Map<String, Object> attributes) {
		Connection conn = sql2o.beginTransaction() ;
		Query query = conn.createQuery(sql.toString()) ;
		executeQuery(query, attributes);
		int res = query.executeUpdate().getResult() ;
		conn.commit() ;
		return res ;
	}
	
	
	private static void executeQuery(Query query, Map<String, Object> params){
		if (null != params && params.size() > 0) {
			Set<String> keys = params.keySet();
			for(String key : keys){
				query.addParameter(key, params.get(key));
			}
		}
	}
}
